import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '../stores/user'
import { isTokenExpired } from '../utils/tokenUtils'
import { usePermissions } from '../stores/permission'
import { generateDynamicRoutes, hasRoutePermission } from './dynamicRoutes'
import Login from '../views/Login.vue'
import Layout from '../views/Layout.vue'
import Dashboard from '../views/Dashboard.vue'
import Profile from '../views/Profile.vue'
import Forbidden from '../views/403.vue'

// 基础路由配置（不需要权限的路由）
const baseRoutes = [
  {
    path: '/',
    redirect: '/dashboard'
  },
  {
    path: '/login',
    name: 'Login',
    component: Login,
    meta: {
      requiresAuth: false
    }
  },
  {
    path: '/403',
    name: 'Forbidden',
    component: Forbidden,
    meta: {
      requiresAuth: false
    }
  },
  {
    path: '/',
    name: 'Layout',
    component: Layout,
    meta: {
      requiresAuth: true
    },
    children: [
      {
        path: '/dashboard',
        name: 'Dashboard',
        component: Dashboard,
        meta: {
          title: '仪表板'
        }
      },
      {
        path: '/profile',
        name: 'Profile',
        component: Profile,
        meta: {
          title: '个人中心',
          requiresMenu: true,
          menuPath: '/profile'
        }
      },
      {
        path: '/product/:id',
        name: 'ProductDetail',
        component: () => import('../views/ProductDetail.vue'),
        meta: {
          title: '商品详情',
          requiresAuth: true
        }
      }
    ]
  },
  // 404页面 - 必须放在最后
  {
    path: '/:pathMatch(.*)*',
    name: 'NotFound',
    component: () => import('../views/404.vue'),
    meta: {
      requiresAuth: false
    }
  }
]

// 动态路由将在用户登录后根据权限动态添加
let dynamicRoutesAdded = false
let addedRouteNames = new Set() // 记录已添加的路由名称
let routeLoadingPromise = null // 路由加载Promise，避免重复加载

const router = createRouter({
  history: createWebHistory(),
  routes: baseRoutes
})

/**
 * 添加动态路由
 * @param {Array} menus 用户菜单数据
 */
export function addDynamicRoutes(menus) {
  console.log('addDynamicRoutes 被调用，dynamicRoutesAdded:', dynamicRoutesAdded)
  console.log('传入的菜单数据:', menus)
  
  if (dynamicRoutesAdded) {
    console.log('动态路由已添加，跳过')
    return Promise.resolve() // 避免重复添加
  }
  
  try {
    // 生成动态路由
    const dynamicRoutes = generateDynamicRoutes(menus)
    console.log('生成的动态路由:', dynamicRoutes)
    
    // 添加动态路由到Layout的children中
    dynamicRoutes.forEach(route => {
      try {
        // 检查路由是否已存在
        if (!addedRouteNames.has(route.name)) {
          console.log(`添加路由: ${route.path} -> ${route.name}`)
          // 添加到Layout路由的子路由
          router.addRoute('Layout', route)
          addedRouteNames.add(route.name)
        } else {
          console.log(`路由已存在，跳过: ${route.name}`)
        }
      } catch (error) {
        console.warn(`添加路由 ${route.path} 失败:`, error)
      }
    })
    
    dynamicRoutesAdded = true
    console.log(`成功添加 ${dynamicRoutes.length} 个动态路由`)
    console.log('当前所有路由:', router.getRoutes().map(r => ({ name: r.name, path: r.path })))
    return Promise.resolve()
  } catch (error) {
    console.error('添加动态路由失败:', error)
    return Promise.reject(error)
  }
}

/**
 * 清除动态路由（用于用户退出登录时）
 */
export function clearDynamicRoutes() {
  if (!dynamicRoutesAdded) {
    return
  }
  
  // 清除记录的路由名称
  addedRouteNames.clear()
  dynamicRoutesAdded = false
  routeLoadingPromise = null
  console.log('已清除动态路由标志')
}

// 使用动态路由模块的权限检查函数
function hasMenuPermission(menuPath, userMenus) {
  return hasRoutePermission(menuPath, userMenus)
}

/**
 * 确保动态路由已加载
 * @param {Object} userStore 用户状态
 * @param {Object} userMenus 用户菜单数据
 * @returns {Promise<boolean>} 是否成功加载
 */
async function ensureDynamicRoutesLoaded(userStore, userMenus) {
  // 如果正在加载，等待加载完成
  if (routeLoadingPromise) {
    console.log('路由正在加载中，等待完成...')
    return await routeLoadingPromise
  }

  // 如果已经加载完成，直接返回
  if (dynamicRoutesAdded && userMenus.value && userMenus.value.length > 0) {
    console.log('动态路由已加载完成')
    return true
  }

  // 开始加载路由
  routeLoadingPromise = (async () => {
    try {
      console.log('开始加载动态路由...')
      
      // 如果菜单数据为空，尝试加载权限
      if (!userMenus.value || userMenus.value.length === 0) {
        console.log('菜单数据为空，加载用户权限')
        
        // 动态导入getUserInfo API
        const { getUserInfo } = await import('../api/auth')
        const response = await getUserInfo()

        console.log('获取到的用户信息:', response.data)

        // 设置权限数据
        const { setUserPermissions } = await import('../stores/permission')
        setUserPermissions(
          response.data.buttons || [],
          response.data.menus || [],
          response.data
        )

        // 重置动态路由状态，确保重新加载
        dynamicRoutesAdded = false
        addedRouteNames.clear()

        // 加载动态路由
        if (response.data.menus && response.data.menus.length > 0) {
          console.log('加载动态路由，菜单数量:', response.data.menus.length)
          await addDynamicRoutes(response.data.menus)
          return true
        }
      } else {
        // 确保动态路由已添加
        console.log('使用现有菜单数据加载动态路由')
        await addDynamicRoutes(userMenus.value)
        return true
      }

      return false
    } catch (error) {
      console.error('加载动态路由失败:', error)
      throw error
    } finally {
      // 清除加载Promise
      routeLoadingPromise = null
    }
  })()

  return await routeLoadingPromise
}

// 路由守卫
router.beforeEach(async (to, from, next) => {
  console.log(`路由导航: ${from.path} -> ${to.path}`)

  const userStore = useUserStore()
  const token = localStorage.getItem('token')

  // 检查token是否存在且有效
  const hasValidToken = token && !isTokenExpired(token)

  // 如果访问的是不需要认证的页面
  if (to.meta.requiresAuth === false) {
    if (to.path === '/login' && hasValidToken && userStore.isLoggedIn) {
      // 已登录用户访问登录页，重定向到首页
      console.log('已登录用户访问登录页，重定向到首页')
      next('/dashboard')
      return
    }
    next()
    return
  }

  // 需要认证的页面
  if (!hasValidToken) {
    // token无效，清除状态并跳转登录页
    console.log('Token无效，跳转到登录页')
    userStore.logout()
    next('/login')
    return
  }

  // 确保用户状态已初始化
  if (!userStore.isLoggedIn || !userStore.isInitialized) {
    console.log('初始化用户状态')
    try {
      const success = userStore.syncFromStorage()
      userStore.setInitialized(true)
      if (!success) {
        userStore.logout()
        next('/login')
        return
      }
    } catch (error) {
      console.error('用户状态同步失败:', error)
      userStore.logout()
      next('/login')
      return
    }
  }

  // 获取权限状态
  const { userMenus } = usePermissions()
  console.log('当前菜单数据状态:', userMenus.value ? userMenus.value.length : 'null')

  // 尝试确保动态路由已加载
  try {
    const routesLoaded = await ensureDynamicRoutesLoaded(userStore, userMenus)
    console.log('动态路由加载结果:', routesLoaded)
  } catch (error) {
    console.error('加载动态路由失败:', error)
    // 如果是权限相关错误，跳转到登录页
    if (error.response && (error.response.status === 401 || error.response.status === 403)) {
      userStore.logout()
      next('/login')
      return
    }
    // 其他错误，继续路由导航，让404页面处理
  }

  console.log('动态路由添加状态:', dynamicRoutesAdded)
  console.log('已添加的路由名称:', Array.from(addedRouteNames))

  // 检查路由是否匹配
  const isRouteMatched = to.matched.length > 0 && !to.matched.some(record => record.name === 'NotFound')
  console.log(`路由匹配状态: ${isRouteMatched}, matched.length: ${to.matched.length}`)

  // 如果路由未匹配，进行特殊处理
  if (!isRouteMatched) {
    console.log(`路由未匹配: ${to.path}`)

    // 检查是否是有权限的路由
    if (userMenus.value && hasMenuPermission(to.path, userMenus.value)) {
      console.log('有权限但路由未加载，尝试强制重新导航')

      // 强制重新加载动态路由
      dynamicRoutesAdded = false
      addedRouteNames.clear()
      routeLoadingPromise = null

      try {
        await ensureDynamicRoutesLoaded(userStore, userMenus)

        // 使用replace方式重新导航，避免历史记录问题
        console.log('路由重新加载成功，重新导航到:', to.path)
        next({ ...to, replace: true })
        return
      } catch (error) {
        console.error('重新加载动态路由失败:', error)
      }
    } else {
      console.log('用户无权限访问该路径:', to.path)
    }

    // 如果没有权限或无法加载路由，继续到404页面
    console.log('路由未找到，将显示404页面')
    next()
    return
  }

  // 检查菜单权限（仅对需要菜单权限的路由）
  if (to.meta.requiresMenu) {
    const menuPath = to.meta.menuPath || to.path
    if (!hasMenuPermission(menuPath, userMenus.value)) {
      console.warn(`用户无权限访问路径: ${to.path}`)
      next('/403')
      return
    }
  }

  console.log('路由守卫检查完成，允许访问:', to.path)
  next()
})

// 调试函数
window.debugRouter = () => {
  console.log('=== 路由调试信息 ===')
  console.log('动态路由添加状态:', dynamicRoutesAdded)
  console.log('已添加的路由名称:', Array.from(addedRouteNames))
  console.log('所有路由:', router.getRoutes().map(r => ({ 
    name: r.name, 
    path: r.path, 
    component: r.component?.name || 'Anonymous'
  })))
  
  const { userMenus } = usePermissions()
  console.log('当前菜单数据:', userMenus.value)
  console.log('===================')
}

export default router 